package net.liteheaven.testfile;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

/**
 * Created by LiangYu on 2018/6/20.
 */
public class FragmentStackActivity extends Activity implements View.OnClickListener, StackEventCallback {

    private Button start;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_fragment_stack);
        start = (Button)findViewById(R.id.start);
        start.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        addFragment(FragmentA.newInstance());
    }

    @Override
    public void onEvent(int page, int event) {
        if (event == 1){
            FragmentManager fm = getFragmentManager();
            fm.popBackStackImmediate();
        }else if (event == 2){
            if (page == 1){
                addFragment(FragmentB.newInstance());
            }else if (page == 2){
                addFragment(FragmentC.newInstance());
            }else if (page == 3){
                getFragmentManager().popBackStackImmediate(FragmentA.class.getSimpleName(), FragmentManager.POP_BACK_STACK_INCLUSIVE);
            }
        }
    }

    private void addFragment(Fragment fragment){
        FragmentManager fm = getFragmentManager();
        String tag = fragment.getClass().getSimpleName();
        Fragment f = fm.findFragmentByTag(tag);
        if (f == null){
            FragmentTransaction transaction = fm.beginTransaction();
            transaction.add(R.id.container, fragment, tag);
            transaction.addToBackStack(tag);
            int id = transaction.commit();
        }
    }
}
